package com.galaxy.service.config;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.support.http.StatViewServlet;
import com.alibaba.druid.support.http.WebStatFilter;
import java.sql.SQLException;
import javax.sql.DataSource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * Druid配置数据源
 * @author caijinbang
 * @date 2018/8/19 11:59
 */
@Configuration
@Slf4j
public class DruidConfig {

  /**
   * 数据源路径
   */
  @Value("${spring.datasource.url}")
  private String url;

  /**
   * 用户名称
   */
  @Value("${spring.datasource.username}")
  private String username;

  /**
   * 数据库密码
   */
  @Value("${spring.datasource.password}")
  private String password;

  /**
   * 驱动名称
   */
  @Value("${spring.datasource.driverClassName}")
  private String driverClassName;

  /**
   * 初始化大小
   */
  @Value("${spring.datasource.initialSize}")
  private int initialSize;

  /**
   * 最小连接数
   */
  @Value("${spring.datasource.minIdle}")
  private int minIdle;

  /**
   * 最大连接数
   */
  @Value("${spring.datasource.maxActive}")
  private int maxActive;

  /**
   * 获取连接等待超时时间
   */
  @Value("${spring.datasource.maxWait}")
  private int maxWait;

  /**
   * 间隔多久才进行一次检测，检测需要关闭的空闲连接，单位是毫秒
   */
  @Value("${spring.datasource.timeBetweenEvictionRunsMillis}")
  private int timeBetweenEvictionRunsMillis;

  /**
   * 一个连接在池中最小生存的时间，单位是毫秒
   */
  @Value("${spring.datasource.minEvictableIdleTimeMillis}")
  private int minEvictableIdleTimeMillis;

  /**
   * SQL查询,用来验证从连接池取出的连接,在将连接返回给调用者之前.
   * 如果指定,则查询必须是一个SQL SELECT并且必须返回至少一行记录
   */
  @Value("${spring.datasource.validationQuery}")
  private String validationQuery;

  /**
   * 指明连接是否被空闲连接回收器(如果有)进行检验.如果检测失败,则连接将被从池中去除.
   * 注意: 设置为true后如果要生效,validationQuery参数必须设置为非空字符串
   */
  @Value("${spring.datasource.testWhileIdle}")
  private boolean testWhileIdle;

  /**
   *  指明是否在从池中取出连接前进行检验,如果检验失败,则从池中去除连接并尝试取出另一个.
   *  注意: 设置为true后如果要生效,validationQuery参数必须设置为非空字符串
   */
  @Value("${spring.datasource.testOnBorrow}")
  private boolean testOnBorrow;

  /**
   * 指明是否在归还到池中前进行检验
   */
  @Value("${spring.datasource.testOnReturn}")
  private boolean testOnReturn;

  /**
   * 是否PSCache
   */
  @Value("${spring.datasource.poolPreparedStatements}")
  private boolean poolPreparedStatements;

  /**
   * 指定每个连接上PSCache的大小
   */
  @Value("${spring.datasource.maxPoolPreparedStatementPerConnectionSize}")
  private int maxPoolPreparedStatementPerConnectionSize;

  /**
   * 配置监控统计拦截的filters，去掉后监控界面SQL无法进行统计，’wall’用于防火墙
   */
  @Value("${spring.datasource.filters}")
  private String filters;

  /**
   * 通过connectProperties属性来打开mergeSql功能；慢SQL记录
   */
  @Value("{spring.datasource.connectionProperties}")
  private String connectionProperties;


  /**
   * 获取数据源,设置数据源属性
   * @return datasource
   */
  @Bean
  public DataSource getDataSource() {
    DruidDataSource datasource = new DruidDataSource();
    datasource.setUrl(url);
    datasource.setUsername(username);
    datasource.setPassword(password);
    datasource.setDriverClassName(driverClassName);
    datasource.setInitialSize(initialSize);
    datasource.setMinIdle(minIdle);
    datasource.setMaxActive(maxActive);
    datasource.setMaxWait(maxWait);
    datasource.setTimeBetweenEvictionRunsMillis(timeBetweenEvictionRunsMillis);
    datasource.setMinEvictableIdleTimeMillis(minEvictableIdleTimeMillis);
    datasource.setValidationQuery(validationQuery);
    datasource.setTestWhileIdle(testWhileIdle);
    datasource.setTestOnBorrow(testOnBorrow);
    datasource.setTestOnReturn(testOnReturn);
    datasource.setPoolPreparedStatements(poolPreparedStatements);
    datasource.setMaxPoolPreparedStatementPerConnectionSize(maxPoolPreparedStatementPerConnectionSize);
    datasource.setConnectionProperties(connectionProperties);
    try {
      datasource.setFilters(filters);
    } catch (SQLException e) {
      log.error("druid configuration initialization filter", e);
    }
    return datasource;
  }


  /**
   * 注册ServletRegistrationBean
   * @return ServletRegistrationBean
   */
  @Bean
  public ServletRegistrationBean registrationBean() {
    ServletRegistrationBean bean = new ServletRegistrationBean(new StatViewServlet(), "/druid/*");
    //白名单,多个ip逗号隔开
    bean.addInitParameter("allow", "127.0.0.1");
    //IP黑名单 (存在共同时，deny优先于allow)
    bean.addInitParameter("deny", "192.168.1.110");
    bean.addInitParameter("loginUsername", "admin");
    bean.addInitParameter("loginPassword", "123456");
    //是否能够重置数据.
    bean.addInitParameter("resetEnable", "false");
    return bean;
  }

  /**
   * 注册FilterRegistrationBean
   * @return FilterRegistrationBean
   */
  @Bean
  public FilterRegistrationBean druidStatFilter() {
    FilterRegistrationBean bean = new FilterRegistrationBean(new WebStatFilter());
    //添加过滤规则.
    bean.addUrlPatterns("/*");
    //添加不需要忽略的格式信息.
    bean.addInitParameter("exclusions","*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*");
    return bean;
  }
}
